import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from "ant-design-vue";
import { userLogin, userLoginByPhone } from '@/utils/api'
import { setToken, removeToken } from '@/utils/auth'
export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref({})
    const setUserInfo = data => {
      userInfo.value = data
    }
    const router = useRouter()

    const login = async data => {
      let spm = new Date().getTime()
      localStorage.setItem('SPM', spm)
      console.log('data: ==》', data)
      if (data.loginType == 'account') {
        console.log('账户登录', 111)
        const params = {
          phone: data.username,
          password: data.password,
          remember: data.remember,
        }
        userLogin(params)
          .then(res => {
            console.log('成功', res)
            if (res.code === 1) {
              setUserInfo(Object.assign({}, data, res))
              setToken(res.data.access_token)
              // localStorage.setItem('spm', spm)
              checkAndRedirect() // 登录成功后检查并跳转
            }else{
              message.error(res.msg);
              return Promise.reject(res)
            }
          })
          .catch(err => {
            console.log('失败', err)
          })
      } else {
        const params = {
          phone: data.phone,
          code: data.captcha,
          spm:spm,
        }
        console.log('验证码登录', 222)
        console.log('params: ', params)
        userLoginByPhone(params)
          .then(res => {
            if(res.code === 1){
              console.log('成功', res)
              setUserInfo(Object.assign({}, data, res))
              setToken(res.data.access_token)
              checkAndRedirect() // 登录成功后检查并跳转 
            }else{
              message.error(res.msg);
              return Promise.reject(res)
            }
          })
          .catch(err => {
            console.log('失败', err)
          })
      }
      // 写登录请求
      // await router.push('/')
    }
    const logout = async () => {
      await router.push('/login')
      userInfo.value = {}
      removeToken()
    }
    // 检查用户是否登录并跳转
    const checkAndRedirect = () => {
      console.log('Object.keys(userInfo.value: ', Object.keys(userInfo.value))
      if (Object.keys(userInfo.value).length > 0) {
        router.push('/signIn?type=selectType')
      } else {
        router.push('/login')
      }
    }

    return { userInfo, setUserInfo, login, logout }
  },
  { persist: true },
)
